import React, { Component } from 'react';

import RecomBookService from 'services/RecomBook';
import CommonService from '../../../services/Common';

import { getDatas } from 'utils/tools';

import { RECOM_BOOK_TH } from 'config/table_config';

import ListTitle from 'components/common/ListTitle';
import TableHead from 'components/common/TableHead';
import TableBody from './TableBody';

import './index.scss';

const recomBookService = new RecomBookService(),
      commonService = new CommonService();

export default class RecomCourse extends Component {
  constructor(props) {
    super(props)

    this.state = {
      title: '推荐书本管理',
      recomBookData: []
    }
  }

  //推荐课程上下架
  onStatusClick (bid, index) {
    const { recomBookData } = this.state,
          status = recomBookData[index].status;

    const cfm = window.confirm(`确认要${ status ? '下架' : '上架' }该课程吗？`);
    
    if (cfm) {
        switch (status) {
          case 1:
            recomBookData[index].status = 0;
            break;
          case 0:
            recomBookData[index].status = 1;
            break;
          default:
            break;
        }
      
        this.setState({
    
          recomBookData
    
        }, async () => {
    
          const result = await commonService.changeStatus({
            id: bid,
            status: recomBookData[index].status,
            field: 'RECOM_BOOK'
          });
          
          const errorCode = result.error_code,//后端返回的0表示是执行成功的操作
                status = recomBookData[index].status;
    
          if (errorCode !== 0) {
            alert( status ? '该课程上架失败' : '该课程下架失败' );
            return;
          }
    
          //status为1表示上架状态，0表示下架状态
          // alert( status ? '上架成功' : '下架成功' );
        });

    };
  }

  //获取推荐的书本
  async getRecomBookData () {
     const result = await recomBookService.getRecomBookData(),
           errorCode = result.error_code,
           data = result.data,
           { history } = this.props;

     getDatas(errorCode, data, history, () => {

       this.setState({
        recomBookData: data
       })
   
     })
  }

  componentDidMount () {
    this.getRecomBookData();
  }

  onRefreshData () {
    this.getRecomBookData();//这种方式好很多很多，下面那种方式只是给用户看的，肉眼能看到刷新，哈哈~
    //  window.location.reload();
  }


  render () {
    const { title, recomBookData } = this.state;
    return (
      <div className="list-container">
        <ListTitle 
          title={ title }
          onRefreshData={ this.onRefreshData.bind(this) }
        />

        <table className="list-table">
          <TableHead
            thData={ RECOM_BOOK_TH }
          />
          <TableBody 
            recomBookData={ recomBookData }
            onStatusClick={ this.onStatusClick.bind(this)}
          />
        </table>
      </div>
    );
  }
}